/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package daos;

import businessObjects.Cliente;
import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import daos.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import businessObjects.Pais;
import businessObjects.Pauta;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author williamprado
 */
public class ClienteDAO {

    public ClienteDAO() {
        //emf = Persistence.createEntityManagerFactory("Adz-ejbPU");
    }
    //private EntityManagerFactory emf = null;

    /*public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }*/

    /*public void create(Cliente cliente) throws PreexistingEntityException, Exception {
        if (cliente.getPautaCollection() == null) {
            cliente.setPautaCollection(new ArrayList<Pauta>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pais pais = cliente.getPais();
            if (pais != null) {
                pais = em.getReference(pais.getClass(), pais.getCcode());
                cliente.setPais(pais);
            }
            Collection<Pauta> attachedPautaCollection = new ArrayList<Pauta>();
            for (Pauta pautaCollectionPautaToAttach : cliente.getPautaCollection()) {
                pautaCollectionPautaToAttach = em.getReference(pautaCollectionPautaToAttach.getClass(), pautaCollectionPautaToAttach.getIdPauta());
                attachedPautaCollection.add(pautaCollectionPautaToAttach);
            }
            cliente.setPautaCollection(attachedPautaCollection);
            em.persist(cliente);
            if (pais != null) {
                pais.getClienteCollection().add(cliente);
                pais = em.merge(pais);
            }
            for (Pauta pautaCollectionPauta : cliente.getPautaCollection()) {
                Cliente oldLoginClienteOfPautaCollectionPauta = pautaCollectionPauta.getLoginCliente();
                pautaCollectionPauta.setLoginCliente(cliente);
                pautaCollectionPauta = em.merge(pautaCollectionPauta);
                if (oldLoginClienteOfPautaCollectionPauta != null) {
                    oldLoginClienteOfPautaCollectionPauta.getPautaCollection().remove(pautaCollectionPauta);
                    oldLoginClienteOfPautaCollectionPauta = em.merge(oldLoginClienteOfPautaCollectionPauta);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCliente(cliente.getLogin()) != null) {
                throw new PreexistingEntityException("Cliente " + cliente + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }*/

    public void create(Cliente cliente, EntityManager em) throws PreexistingEntityException, Exception {
        if (cliente.getPautaCollection() == null) {
            cliente.setPautaCollection(new ArrayList<Pauta>());
        }
        //EntityManager em = null;
        try {
            //em = getEntityManager();
            //em.getTransaction().begin();
            Pais pais = cliente.getPais();
            if (pais != null) {
                pais = em.getReference(pais.getClass(), pais.getCcode());
                cliente.setPais(pais);
            }
            Collection<Pauta> attachedPautaCollection = new ArrayList<Pauta>();
            for (Pauta pautaCollectionPautaToAttach : cliente.getPautaCollection()) {
                pautaCollectionPautaToAttach = em.getReference(pautaCollectionPautaToAttach.getClass(), pautaCollectionPautaToAttach.getIdPauta());
                attachedPautaCollection.add(pautaCollectionPautaToAttach);
            }
            cliente.setPautaCollection(attachedPautaCollection);
            em.persist(cliente);
            if (pais != null) {
                pais.getClienteCollection().add(cliente);
                pais = em.merge(pais);
            }
            for (Pauta pautaCollectionPauta : cliente.getPautaCollection()) {
                Cliente oldLoginClienteOfPautaCollectionPauta = pautaCollectionPauta.getLoginCliente();
                pautaCollectionPauta.setLoginCliente(cliente);
                pautaCollectionPauta = em.merge(pautaCollectionPauta);
                if (oldLoginClienteOfPautaCollectionPauta != null) {
                    oldLoginClienteOfPautaCollectionPauta.getPautaCollection().remove(pautaCollectionPauta);
                    oldLoginClienteOfPautaCollectionPauta = em.merge(oldLoginClienteOfPautaCollectionPauta);
                }
            }
            //em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCliente(cliente.getLogin(), em) != null) {
                throw new PreexistingEntityException("Cliente " + cliente + " already exists.", ex);
            }
            throw ex;
        }
    }

    /*public void edit(Cliente cliente) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente persistentCliente = em.find(Cliente.class, cliente.getLogin());
            Pais paisOld = persistentCliente.getPais();
            Pais paisNew = cliente.getPais();
            Collection<Pauta> pautaCollectionOld = persistentCliente.getPautaCollection();
            Collection<Pauta> pautaCollectionNew = cliente.getPautaCollection();
            List<String> illegalOrphanMessages = null;
            for (Pauta pautaCollectionOldPauta : pautaCollectionOld) {
                if (!pautaCollectionNew.contains(pautaCollectionOldPauta)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Pauta " + pautaCollectionOldPauta + " since its loginCliente field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (paisNew != null) {
                paisNew = em.getReference(paisNew.getClass(), paisNew.getCcode());
                cliente.setPais(paisNew);
            }
            Collection<Pauta> attachedPautaCollectionNew = new ArrayList<Pauta>();
            for (Pauta pautaCollectionNewPautaToAttach : pautaCollectionNew) {
                pautaCollectionNewPautaToAttach = em.getReference(pautaCollectionNewPautaToAttach.getClass(), pautaCollectionNewPautaToAttach.getIdPauta());
                attachedPautaCollectionNew.add(pautaCollectionNewPautaToAttach);
            }
            pautaCollectionNew = attachedPautaCollectionNew;
            cliente.setPautaCollection(pautaCollectionNew);
            cliente = em.merge(cliente);
            if (paisOld != null && !paisOld.equals(paisNew)) {
                paisOld.getClienteCollection().remove(cliente);
                paisOld = em.merge(paisOld);
            }
            if (paisNew != null && !paisNew.equals(paisOld)) {
                paisNew.getClienteCollection().add(cliente);
                paisNew = em.merge(paisNew);
            }
            for (Pauta pautaCollectionNewPauta : pautaCollectionNew) {
                if (!pautaCollectionOld.contains(pautaCollectionNewPauta)) {
                    Cliente oldLoginClienteOfPautaCollectionNewPauta = pautaCollectionNewPauta.getLoginCliente();
                    pautaCollectionNewPauta.setLoginCliente(cliente);
                    pautaCollectionNewPauta = em.merge(pautaCollectionNewPauta);
                    if (oldLoginClienteOfPautaCollectionNewPauta != null && !oldLoginClienteOfPautaCollectionNewPauta.equals(cliente)) {
                        oldLoginClienteOfPautaCollectionNewPauta.getPautaCollection().remove(pautaCollectionNewPauta);
                        oldLoginClienteOfPautaCollectionNewPauta = em.merge(oldLoginClienteOfPautaCollectionNewPauta);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = cliente.getLogin();
                if (findCliente(id) == null) {
                    throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }*/

    public void edit(Cliente cliente, EntityManager em) throws IllegalOrphanException, NonexistentEntityException, Exception {
        //EntityManager em = null;
        try {
            //em = getEntityManager();
            //em.getTransaction().begin();
            Cliente persistentCliente = em.find(Cliente.class, cliente.getLogin());
            Pais paisOld = persistentCliente.getPais();
            Pais paisNew = cliente.getPais();
            Collection<Pauta> pautaCollectionOld = persistentCliente.getPautaCollection();
            Collection<Pauta> pautaCollectionNew = cliente.getPautaCollection();
            List<String> illegalOrphanMessages = null;
            for (Pauta pautaCollectionOldPauta : pautaCollectionOld) {
                if (!pautaCollectionNew.contains(pautaCollectionOldPauta)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Pauta " + pautaCollectionOldPauta + " since its loginCliente field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (paisNew != null) {
                paisNew = em.getReference(paisNew.getClass(), paisNew.getCcode());
                cliente.setPais(paisNew);
            }
            Collection<Pauta> attachedPautaCollectionNew = new ArrayList<Pauta>();
            for (Pauta pautaCollectionNewPautaToAttach : pautaCollectionNew) {
                pautaCollectionNewPautaToAttach = em.getReference(pautaCollectionNewPautaToAttach.getClass(), pautaCollectionNewPautaToAttach.getIdPauta());
                attachedPautaCollectionNew.add(pautaCollectionNewPautaToAttach);
            }
            pautaCollectionNew = attachedPautaCollectionNew;
            cliente.setPautaCollection(pautaCollectionNew);
            cliente = em.merge(cliente);
            if (paisOld != null && !paisOld.equals(paisNew)) {
                paisOld.getClienteCollection().remove(cliente);
                paisOld = em.merge(paisOld);
            }
            if (paisNew != null && !paisNew.equals(paisOld)) {
                paisNew.getClienteCollection().add(cliente);
                paisNew = em.merge(paisNew);
            }
            for (Pauta pautaCollectionNewPauta : pautaCollectionNew) {
                if (!pautaCollectionOld.contains(pautaCollectionNewPauta)) {
                    Cliente oldLoginClienteOfPautaCollectionNewPauta = pautaCollectionNewPauta.getLoginCliente();
                    pautaCollectionNewPauta.setLoginCliente(cliente);
                    pautaCollectionNewPauta = em.merge(pautaCollectionNewPauta);
                    if (oldLoginClienteOfPautaCollectionNewPauta != null && !oldLoginClienteOfPautaCollectionNewPauta.equals(cliente)) {
                        oldLoginClienteOfPautaCollectionNewPauta.getPautaCollection().remove(pautaCollectionNewPauta);
                        oldLoginClienteOfPautaCollectionNewPauta = em.merge(oldLoginClienteOfPautaCollectionNewPauta);
                    }
                }
            }
            //em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = cliente.getLogin();
                if (findCliente(id, em) == null) {
                    throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
    }

    /*public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente cliente;
            try {
                cliente = em.getReference(Cliente.class, id);
                cliente.getLogin();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Pauta> pautaCollectionOrphanCheck = cliente.getPautaCollection();
            for (Pauta pautaCollectionOrphanCheckPauta : pautaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Cliente (" + cliente + ") cannot be destroyed since the Pauta " + pautaCollectionOrphanCheckPauta + " in its pautaCollection field has a non-nullable loginCliente field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Pais pais = cliente.getPais();
            if (pais != null) {
                pais.getClienteCollection().remove(cliente);
                pais = em.merge(pais);
            }
            em.remove(cliente);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }*/

    public void destroy(String id, EntityManager em) throws IllegalOrphanException, NonexistentEntityException, Exception {
        //EntityManager em = null;
        try {
            //em = getEntityManager();
            //em.getTransaction().begin();
            Cliente cliente;
            try {
                cliente = em.getReference(Cliente.class, id);
                cliente.getLogin();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Pauta> pautaCollectionOrphanCheck = cliente.getPautaCollection();
            for (Pauta pautaCollectionOrphanCheckPauta : pautaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Cliente (" + cliente + ") cannot be destroyed since the Pauta " + pautaCollectionOrphanCheckPauta + " in its pautaCollection field has a non-nullable loginCliente field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Pais pais = cliente.getPais();
            if (pais != null) {
                pais.getClienteCollection().remove(cliente);
                pais = em.merge(pais);
            }
            em.remove(cliente);
            //em.getTransaction().commit();
        } catch(Exception e) {
            throw e;
        }
    }

    /*public List<Cliente> findClienteEntities() {
        return findClienteEntities(true, -1, -1);
    }*/

    public List<Cliente> findClienteEntities(EntityManager em) throws Exception {
        return findClienteEntities(true, -1, -1, em);
    }

    /*public List<Cliente> findClienteEntities(int maxResults, int firstResult) {
        return findClienteEntities(false, maxResults, firstResult);
    }*/

    public List<Cliente> findClienteEntities(int maxResults, int firstResult, EntityManager em) throws Exception {
        return findClienteEntities(false, maxResults, firstResult, em);
    }

    /*private List<Cliente> findClienteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Cliente as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }*/

    private List<Cliente> findClienteEntities(boolean all, int maxResults, int firstResult, EntityManager em) throws Exception {
        //EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Cliente as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(Exception e) {
            throw e;
        }
    }

    /*public Cliente findCliente(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cliente.class, id);
        } finally {
            em.close();
        }
    }*/

    public Cliente findCliente(String id, EntityManager em) throws Exception {
        //EntityManager em = getEntityManager();
        try {
            return em.find(Cliente.class, id);
        } catch(Exception e) {
            System.out.println("fallo al buscar");
            throw e;
        }
    }

    /*public int getClienteCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Cliente as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }*/

    public int getClienteCount(EntityManager em) throws Exception {
        //EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Cliente as o");
            return ((Long) q.getSingleResult()).intValue();
        } catch(Exception e) {
            throw e;
        }
    }

}
